#include <stdio.h>
#include "lv_conf.h"
#include <sys/time.h>
#include <sdl/sdl.h>
#include "lvgl/lvgl.h"
#include <sys/time.h>
#include <unistd.h>


#define  DISP_BUF_SIZE  800*480*2


void init_input_output()
{
    //初始化显示sdl
    sdl_init();
    //输入接口
    static lv_color_t buf[DISP_BUF_SIZE]; //显示缓冲区
    static lv_color_t buf1[DISP_BUF_SIZE]; //显示缓冲区
    static lv_disp_draw_buf_t disp_buf;
    lv_disp_draw_buf_init(&disp_buf, buf, buf1, DISP_BUF_SIZE);

    //设置显示缓冲区属性
    static lv_disp_drv_t disp_drv;
    lv_disp_drv_init(&disp_drv);
    disp_drv.draw_buf = &disp_buf;
    disp_drv.flush_cb = sdl_display_flush;
    disp_drv.hor_res = 800;
    disp_drv.ver_res = 480;
    lv_disp_drv_register(&disp_drv);

    static lv_indev_drv_t indev_drv_1;
    lv_indev_drv_init(&indev_drv_1); //基本初始化
    indev_drv_1.type = LV_INDEV_TYPE_POINTER; //设置输入事件类型
    indev_drv_1.read_cb = sdl_mouse_read; //设置具体采集输入数据接口

    //设置具体采集输入数据接口
    lv_indev_drv_t *mouse_indev = lv_indev_drv_register(&indev_drv_1); 
}

/*Set in lv_conf.h as `LV_TICK_CUSTOM_SYS_TIME_EXPR`*/
uint32_t custom_tick_get(void)
{
    static uint64_t start_ms = 0;
    if(start_ms == 0) {
        struct timeval tv_start;
        gettimeofday(&tv_start, NULL);
        start_ms = (tv_start.tv_sec * 1000000 + tv_start.tv_usec) / 1000;
    }
    struct timeval tv_now;
    gettimeofday(&tv_now, NULL);
    uint64_t now_ms;
    now_ms = (tv_now.tv_sec * 1000000 + tv_now.tv_usec) / 1000;

    uint32_t time_ms = now_ms - start_ms;
    return time_ms;
}

static int i = 0;
//事件回调函数
void button_fun_1(lv_event_t *e){
    //获取事件类型
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED){
    i++;
    printf("事件发生次数%d\n",i);
    }
}

void button_fun(lv_event_t *e){
    i++;
    printf("事件发生次数%d\n",i);
}

//事件回调函数
void mainwindow_fun(){
    printf("父窗口事件\n");
}

int main(void)
{   
    //初始化lvgl
    lv_init();
    //初始化输入接口
    init_input_output(); 
    //界面测试
    lv_obj_t *mainwindow = lv_obj_create(lv_scr_act()); //在屏幕上出创建一个窗口
    lv_obj_set_size(mainwindow, 600, 400);
    //在窗口上放置一个窗口
    lv_obj_t *button =  lv_btn_create(mainwindow);
    lv_obj_set_size(button, 100, 50);
    lv_obj_align(button, LV_ALIGN_CENTER, 0, 0);
    //设置按钮的文本
    lv_obj_t *label = lv_label_create(button);
    lv_label_set_text(label, "Click me");
    lv_obj_center(label);

    //添加一个事件
    lv_obj_add_event_cb(button, button_fun, LV_EVENT_CLICKED, NULL);
    lv_obj_add_event_cb(mainwindow, mainwindow_fun, LV_EVENT_CLICKED, NULL);

    //设置事件冒泡
    lv_obj_add_flag(button, LV_OBJ_FLAG_EVENT_BUBBLE);

    while(1) {
        lv_timer_handler();
        usleep(5000);
    }
    
}